package com.example.image;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.example.image.adapter.AdapterImage;
import com.example.image.util.ImageUtil;

public class ImageBrowse extends Activity {
	private GridView gvImage;
	private AdapterImage adapter;
	private ArrayList<String> imagePaths; // 图片路径列表
	private int width; // 屏幕的宽

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); // 注意要在setContentView方法之前设置
		setContentView(R.layout.image_browse);
		setProgressBarIndeterminateVisibility(true); // 控制显示与隐藏
		Display display = getWindowManager().getDefaultDisplay();
		width = display.getWidth();
		String path = getIntent().getStringExtra("path");
		setTitle(path);
		imagePaths = getIntent().getStringArrayListExtra("imagepaths");
		gvImage = (GridView) findViewById(R.id.gv_image_browse);
		adapter = new AdapterImage(this, width);
		gvImage.setAdapter(adapter);
		gvImage.setOnItemClickListener(listener);
		new LoadImage().execute();
	}

	private OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent = new Intent(ImageBrowse.this, ImageShow.class);
			intent.putExtra("imagepaths", imagePaths);
			intent.putExtra("position", position);
			startActivity(intent);
		}
	};

	class LoadImage extends AsyncTask<String, Bitmap, Integer> {

		@Override
		protected Integer doInBackground(String... params) {
			for (int i = 0; i < imagePaths.size(); i++) {
				Bitmap bitmap = ImageUtil.getBitmap(imagePaths.get(i),
						width / 3);
				publishProgress(bitmap);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			setProgressBarIndeterminateVisibility(false); // 控制显示与隐藏
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(Bitmap... values) {
			adapter.add(values);
			super.onProgressUpdate(values);
		}

	}
}
